package com.frame.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frame.common.core.entity.SysDictData;
import com.frame.common.core.entity.SysDictType;
import com.frame.common.utils.DictUtils;
import com.frame.exception.CustomException;
import com.frame.stant.constans.UserConstants;
import com.frame.system.mapper.SysDictDataMapper;
import com.frame.system.mapper.SysDictTypeMapper;
import com.frame.system.service.ISysDictTypeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 字典 业务层处理
 *
 * @author ruoyi
 */
@Service
@AllArgsConstructor
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper,SysDictType> implements ISysDictTypeService {

    private final SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        List<SysDictType> dictTypeList = baseMapper.selectList(Wrappers.lambdaQuery());
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictData = dictDataMapper.selectDictDataByType(dictType.getDictType());
            DictUtils.setDictCache(dictType.getDictType(), dictData);
        }
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public IPage<SysDictType> selectDictTypeList(IPage page, SysDictType dictType) {
        List<SysDictType> sysDictTypes = baseMapper.selectDictTypeList(page, dictType);
        return page.setRecords(sysDictTypes);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return baseMapper.selectList(Wrappers.lambdaQuery());
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictData = DictUtils.getDictCache(dictType);
        if (CollectionUtil.isNotEmpty(dictData)) {
            return dictData;
        }
        dictData = dictDataMapper.selectDictDataByType(dictType);
        if (CollectionUtil.isNotEmpty(dictData)) {
            DictUtils.setDictCache(dictType, dictData);
            return dictData;
        }
        return null;
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     * @return 结果
     */
    @Override
    public int deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = baseMapper.selectOne(Wrappers.<SysDictType>lambdaQuery().eq(SysDictType::getDictId,dictId));
            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
        }
        int count = baseMapper.deleteBatchIds(Arrays.asList(dictIds));
        if (count > 0) {
            DictUtils.clearDictCache();
        }
        return count;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dictType) {
        int row = baseMapper.insert(dictType);
        if (row > 0) {
            DictUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDictType(SysDictType dictType) {
        SysDictType oldDict = baseMapper.selectOne(Wrappers.<SysDictType>lambdaQuery().eq(SysDictType::getDictId, dictType.getDictId()));
        baseMapper.update(new SysDictType().setDictType(dictType.getDictType()),Wrappers.<SysDictType>lambdaUpdate().eq(SysDictType::getDictType,oldDict.getDictType()));
        int row = baseMapper.updateById(dictType);
        if (row > 0) {
            DictUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        Long dictId = Objects.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = baseMapper.checkDictTypeUnique(dict.getDictType());
        if (Objects.nonNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
